/*
 * rewarn_nlist.cc
 *
 *  Created on: 2009-5-26
 *      Author: tulai
 */

#include "rewarn_nlist.h"

rewarn_nlist::rewarn_nlist()
{
   size_ = 0;
}

void
rewarn_nlist::remove(u_int16_t index)
{
  if (index < size_ - 1)
    {
      for (u_int16_t i = index; i < size_ - 1; i++)
        nlist[i] = nlist[i + 1];
      size_ -= 1;
    }
  else if (index == size_ - 1)
    {
      size_ -= 1;
    }
}

void
rewarn_nlist::insert(node_state_t node_state_)
{
  if (isfull())
    remove(0);
  nlist[size_] = node_state_;
  size_++;
  return;
}

int
rewarn_nlist::find_node_by_address(nsaddr_t addr_)
{
  for (int i = 0; i < size_; i++)
    {
      if (nlist[i].addr_ == addr_)
        return i;
    }
  return -1;
}

node_state_t*
rewarn_nlist::get(u_int16_t index)
{
  return &nlist[index];
}

u_int16_t
rewarn_nlist::getsize()
{
  return size_;
}

bool
rewarn_nlist::isfull()
{
  return (size_ == MAXNEIGHBORLIST);
}

rewarn_rlist::rewarn_rlist()
{
  rhead = NULL;
  size = 0;
}

void
rewarn_rlist::insert(nsaddr_t party1, nsaddr_t party2, double abstime)
{

  if (size < MAXRELAY)
    {
      relaylist_t *entry = (relaylist_t *) malloc(sizeof(relaylist_t));
      entry->party1 = party1;
      entry->party2 = party2;
      entry->abstime = abstime;
      entry->next = rhead;
      entry->pre = NULL;
      rhead = entry;
      size++;
    }
}

int
rewarn_rlist::remove(nsaddr_t party1, nsaddr_t party2)
{
  relaylist_t *rcur = rhead;
  int i = 0;

  while (rcur != NULL && rcur->next != NULL)
    {
      if ((rcur->party1 == party1 && rcur->party2 == party2) || (rcur->party1
          == party2 && rcur->party2 == party1))
        {
          rcur->pre->next = rcur->next;
          rcur->next->pre = rcur->pre;
          return i;
        }
      i++;
    }
  return -1;

}

int
rewarn_rlist::find(nsaddr_t party1, nsaddr_t party2)
{
  relaylist_t *rcur = rhead;
  int i = 0;

  while (rcur != NULL && rcur->next != NULL)
    {
      if ((rcur->party1 == party1 && rcur->party2 == party2) || (rcur->party1
          == party2 && rcur->party2 == party1))
        {
         return i;
        }
      i++;
    }
  return -1;

}

void
rewarn_rlist::removehead()
{
  relaylist_t * rtemp = rhead;
  if (rhead != NULL)
    {
      rhead = rhead->next;
      if (rhead != NULL)
        rhead->pre = NULL;
      free(rtemp);
      size--;
    }
}
